package tree;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description: 145. 二叉树的后序遍历
 * User: Li_yizYa
 * Date: 2025/5/21
 * Time: 11:18
 */
public class Solution3 {

    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            ret.add(node.val);
            if (node.left != null) {
                stack.push(node.left);
            }
            if (node.right != null) {
                stack.push(node.right);
            }
        }
        int left = 0;
        int right = ret.size() - 1;
        while (left < right) {
            int tmp = ret.get(left);
            ret.set(left, ret.get(right));
            ret.set(right, tmp);
            left++;
            right--;
        }

        return ret;
    }
    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }
        traversal(root, ret);
        return ret;
    }
    private void traversal(TreeNode root, List<Integer> ret) {
        if (root == null) {
            return;
        }
        traversal(root.left, ret);
        traversal(root.right, ret);
        ret.add(root.val);
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        node1.left = null;
        node1.right = node2;
        node2.left = node3;
        node2.right = null;
        node3.left = null;
        node3.right = null;
        List<Integer> ret = postorderTraversal(node1);
        for (int num : ret) {
            System.out.println(num);
        }
    }
}
